<?php
/**
 * 设计师大赛获奖整屋控制器
 */
namespace Beerus\Modules\DesignerCompetition\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Article;
use Doraemon\model\Member;
use Doraemon\model\ReDesignerCompetition\DcHonorArticle;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\ReDesignerCompetition\DcHonor;

class HonorArticleController extends Controller
{
    const PAGE_SIZE = 30;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_params = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_params['id'])) {
            $condition['id'] = $request_params['id'];
        }
        if (!empty($request_params['dc_year'])) {
            $condition['dc_year'] = $request_params['dc_year'];
        }
        if (!empty($request_params['uid'])) {
            $condition['uid'] = $request_params['uid'];
        }
        if (!empty($request_params['aid'])) {
            $condition['aid'] = $request_params['aid'];
        }
        if (!empty($request_params['honor_id'])) {
            $condition['honor_id'] = $request_params['honor_id'];
        }
        $tips = [];
        return $content
            ->header('获奖整屋管理')
            ->row($tips)
            ->row($this->indexGrid($condition, $page, $page_size));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $page, $page_size)
    {
        $lists = DcHonorArticle::getListBySql($condition, $page, $page_size);
        if ($lists) {
            $aArticleList = Article::select('*', ['aid'=>array_column($lists, 'aid')]);
            $aArticleWithTitle = array_column($aArticleList, 'title', 'aid');
        }
        $aHonorList = DcHonor::select('*', ['data_status' => DcHonor::STATUS_NORMAL]);
        $aHonorWithName = array_column($aHonorList, 'honor_name', 'id');
        $aHonorWithNameWithYear = [];
        foreach ($aHonorList as $honorItem) {
            $aHonorWithNameWithYear[$honorItem['id']] = $honorItem['honor_year'].'-'.$honorItem['honor_name'];
        }
        if ($lists) {
            foreach ($lists as &$honorArticleItem) {
                $honorArticleItem['honor_list'] = array_map(function ($honorId) use ($aHonorWithName) {
                    return $aHonorWithName[$honorId];
                }, explode(',', $honorArticleItem['honor_ids']));
                $honorArticleItem['nick'] = Member::getNickByUid($honorArticleItem['uid']);
                $honorArticleItem['article_title'] = $aArticleWithTitle[$honorArticleItem['aid']];
            }
        }

        $total = DcHonorArticle::cntListBySql($condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size,
        ]);

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params, $aHonorWithNameWithYear) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) use ($aHonorWithNameWithYear) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) use ($aHonorWithNameWithYear) {
                        $filter->equal('id', 'ID')->placeholder('请输入ID');
                        $filter->equal('uid', 'UID')->placeholder('请输入UID');
                        $filter->equal('honor_id', '获得奖项')->select($aHonorWithNameWithYear);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('aid', 'AID')->placeholder('请输入整屋AID');
                        $filter->year('dc_year', '奖项年份');
                    });
                    $filter->expand();
                });
                $grid->column('id', 'id');
                $grid->column('dc_year', '奖项年份');
                $grid->column('user_info', '用户信息')->display(function () {
                    return '<strong>[uid]:</strong>' . $this->uid . "<br>" .
                        '<strong>[昵称]:</strong>' . "<br>" . $this->nick;
                });
                $grid->column('article_info', '整屋信息')->display(function () {
                    return '<strong>[aid]:</strong><a href="https://m.haohaozhu.cn/bangyang/' . $this->aid . '.html?preview=1" target="_blank">' . $this->aid . "</a><br>" .
                        '<strong>[标题]:</strong>' . "<br>" . $this->article_title;
                })->width(400);
                $grid->column('honor_list', '获得奖项')->display(function () {
                    return implode('<br>', $this->honor_list);
                });
            }
        );
        return $gridList;
    }

    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('整屋id', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '获奖整屋列表',
                'url' => route('honor_article.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = DcHonorArticle::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->text('id', 'ID')->setWidth(4, 2)->readOnly();
        }

        $form->text('aid', '整屋id')->setWidth(4, 2)->required('不能为空');
        $form->year('dc_year', '奖项年份')->default(date('Y'))->setWidth(4, 2);
        $form->text('uid', '用户uid')->setWidth(4, 2)->required('不能为空');

        $form->action('/admin/DesignerCompetition/honor_article/save');
        return $form->render();
    }

    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'aid' => $request['aid'],
            'dc_year' => $request['dc_year'],
            'uid' => $request['uid']
        ];
        $cur_time = time();
        if (isset($request['id'])) {
            $data['edit_time'] = $cur_time;
            $rs = DcHonorArticle::update($data, ['id' => $request['id']]);
        } else {
            $item = DcHonorArticle::get('*', ['aid' => $request['aid'], 'uid' => $request['uid'], 'dc_year'=>$request['dc_year']]);
            if (!empty($item)) {
                $error = new MessageBag(['title' => '已存在相同整屋']);
                return back()->with(compact('error'));
            }
            $data['add_time'] = $cur_time;
            $rs = DcHonorArticle::addInfo($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/DesignerCompetition/honor_article')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $honorArticle = DcHonorArticle::get('*', ['id' => $id]);
        if ($honorArticle) {
            DcHonorArticle::delete(['id' => $id]);
        }
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }
}
